package com.zhf.eduuserboot.commons;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2021/2/14 14:29
 */
public class HttpClientUtil {
    public static String doGet(String url){
        return doGet(url, null);
    }

    /**
     * get请求 支持request方式，不支持restful方式
     * @param url
     * @param param
     * @return token
     */
    public static String doGet(String url , Map<String,String> param){
        String result="";
        CloseableHttpResponse response=null;
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            //创建url
            URIBuilder builder = new URIBuilder(url);
            if (param!=null){
                for (String key:param.keySet()){
                    builder.setParameter(key,param.get(key));
                }
            }
            URI uri=builder.build();

            //创建httpget请求
            HttpGet httpGet = new HttpGet(uri);
            //执行请求
            response = httpClient.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();
            System.out.println("响应的状态："+code);
            if (code == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
